package org.jinxing.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jinxing.dao.BorrowsInfoDAO;
import org.jinxing.dao.RolesInfoDAO;
import org.jinxing.dao.UsersInfoDAO;
import org.jinxing.model.BorrowsInfoExample;
import org.jinxing.model.RolesInfo;
import org.jinxing.model.RolesInfoExample;
import org.jinxing.model.UsersInfo;
import org.jinxing.model.UsersInfoExample;
import org.jinxing.model.UsersInfoExample.Criteria;
import org.jinxing.service.RolesService;
import org.jinxing.service.UsersInfoService;
import org.jinxing.utils.JsonUtils;
import org.jinxing.utils.ModelUtils;
import org.jinxing.utils.RequestUtils;
import org.jinxing.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/u")
public class UserController {
	protected static String className = UserController.class.getName();
	protected static Log logger = LogFactory.getLog(className);//日志对象

	@Autowired
	BorrowsInfoDAO borrowsInfoDAO;
	@Autowired
	UsersInfoDAO usersInfoDao;
	@Autowired
	UsersInfoService usersInfoService;
	@Autowired
	RolesService rolesService;
	@Autowired
	RolesInfoDAO rolesInfoDAO;
	/**
	 * 进入用户管理首页
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request,HttpServletResponse response,Model model){
		logger.info("<|>"+className+"<|>index<|><|><|>");
		RolesInfoExample example = new RolesInfoExample();
		example.createCriteria().andIdNotEqualTo(1);
		List<RolesInfo> rolesInfoList = rolesInfoDAO.selectByExample(example);
		model.addAttribute("allRoles", JsonUtils.jsonFromObject(rolesInfoList));
		return "/u/index";
	}
	
	/**
	 * 获取登录用户可见的用户信息组
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/getUsers")
	public @ResponseBody String getUsers(HttpServletRequest request,HttpServletResponse response){
		logger.info("<|>"+className+"<|>getUsers<|><|><|>");
		int pageNo = RequestUtils.getInt(request, "page", 1);
		int pageSize = RequestUtils.getInt(request, "pagesize", 0);
		UsersInfo lgUser = ServletUtils.getLgUser(request);
		
		String userName = request.getParameter("userName");
		List<UsersInfo> list = null;
		{
			UsersInfoExample example = new UsersInfoExample();
			Criteria criteria = example.createCriteria();
			criteria.andRoleidGreaterThan(lgUser.getRoleid());
			if(StringUtils.isNotBlank(userName)){
				criteria.andLgnameLike("%"+userName+"%");
			}
			if(pageSize > 0){
				example.setLimitClauseStart((pageNo-1)*pageSize);
				example.setLimitClauseCount(pageSize);
			}
			example.setOrderByClause(" id desc,roleId asc");
			list = this.usersInfoDao.selectByExample(example);
		}
		int count = usersInfoService.countAllUsersInfo(lgUser.getRoleid());
		
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("Rows", list);
		result.put("Total", count);
		return JsonUtils.jsonFromObject(result);
	}
	
	@RequestMapping("/saveOrUpdate")
	public @ResponseBody String saveOrUpdate(HttpServletRequest request,HttpServletResponse response){
		String json = request.getParameter("json");
		Map<String,Object> result = new HashMap<String,Object>();
		List<Integer> successId = new LinkedList<Integer>();
		List tempList = JsonUtils.listFromJson(json);
		for(Object obj : tempList){
			UsersInfo user = ModelUtils.usersFromJson(JsonUtils.jsonFromObject(obj));
			if(null == user.getOperator()){
				user.setOperator(ServletUtils.getLgUser(request).getId());
			}
			if(null == user.getCreatdate()){
				user.setCreatdate(new Date());
			}
			boolean tempR = this.usersInfoService.saveOrUpdate(user);
			if(tempR){
				successId.add(user.getId());
			}
		}
		result.put("sucessList", successId);
		return JsonUtils.jsonFromObject(result);
	}
	
	@RequestMapping("/toModifyPasswd")
	public String toModifyPasswd(HttpServletRequest request,HttpServletResponse response,Model model){
		logger.info("<|>"+className+"<|>toModifyPasswd<|><|><|>");
		UsersInfo lgUser = ServletUtils.getLgUser(request);
		if(lgUser == null){
			return "/lg/lgIn";
		}
		return "/u/toModifyPasswd";
	}
	
	@RequestMapping("/savePasswd")
	public @ResponseBody String savePasswd(HttpServletRequest request,HttpServletResponse response){
		String oldPass = request.getParameter("oldPass");
		String newPass = request.getParameter("newPass");
		UsersInfo lgUser = ServletUtils.getLgUser(request);
		UsersInfo user = this.usersInfoService.getUsersInfo(lgUser.getLgname(), oldPass);
		if(user == null){
			return "1";
		}
		user.setPasswd(newPass);
		this.usersInfoService.saveOrUpdate(user);
		return "0";
	}
	
	protected int availNum(Integer userId){
		int allNum = this.usersInfoService.getById(userId).getMaxnum();
		BorrowsInfoExample borrowsInfoExample = new BorrowsInfoExample();
		BorrowsInfoExample.Criteria borrowsC = borrowsInfoExample.createCriteria();
		borrowsC.andBorrowerEqualTo(userId);
		borrowsC.andIsbackEqualTo(0);//未归还书籍
		int availNum = allNum - this.borrowsInfoDAO.selectCountByExample(borrowsInfoExample);
		return availNum;
	}
	
	@RequestMapping("/getUser/{lgName}")
	public @ResponseBody String getUser(HttpServletRequest request,HttpServletResponse response,@PathVariable String lgName){
		UsersInfo user = this.usersInfoService.getByLgName(lgName);
		if(user != null){
			user.setMaxnum(availNum(user.getId()));
		}
		return JsonUtils.jsonFromObject(user);
	}

}
